import React from 'react';
import { connect } from 'react-redux'
import util from '../../util'
import cx from 'classnames'
import { bindActionCreators } from 'redux'
import * as okrAction from '../../actions/okr.action'
import { resetUser } from '../../actions/user.action'
import { resetTeam } from '../../actions/team.action'
import style from './style.objective-detail';
import { fetchAtList, clearAtList } from '../../actions/home.action'
import ObjectiveItem from './ObjectiveItem';
import ObjectiveCreate from './ObjectiveCreate';
import ObjectiveNote, { pageSize as commentsPageSize } from './ObjectiveNote';
import ObjectiveRelative from './ObjectiveRelative';
import { Link } from 'sq-ui';
import { Checkbox, Modal, info, error, success } from '../../ui-components';

import {
  createKeyResult,
  cancelRequestCreateItem,
  checkItemInput,
  requestEditObjective,
  requestEditKeyResult,
  cancelRequestEditItem,
  requestCreateKeyResult,
  updateObjective,
  updateKeyResult,
} from './Objective';

let preObjFlag = true, preKrFlag = true;

// 点赞目标
function likeObjective(obj) {
  const { okr, profile } = this.props;
  let { objective } = okr;
  let { userId } = profile;
  if(!preObjFlag) return;
  preObjFlag = false;
  const { orgId, objectiveId } = obj;
  let arg = {
    userId, orgId, okrId: objectiveId, keyResultId: null, type: 0, comment: ""
  };
  this.props.actions.updateThumpBub(arg, (res) => {
    this.fetchContent();
    preObjFlag = true;
  });
}

// 点赞结果
function likeKeyResult(kr) {
  const { okr, profile } = this.props;
  let { objective } = okr;
  let { userId } = profile;
  if(!preKrFlag) return;
  preKrFlag = false;
  const { orgId, objectiveId, keyResultId} = kr;
  let arg = {
    userId, orgId, okrId: objectiveId, keyResultId, type: 1, comment: ""
  };
  this.props.actions.updateThumpBub(arg, (res) => {
    this.fetchContent();
    preKrFlag = true;
  });
}

export default
@connect(({ okr, app }) => ({ okr, app }), dispatch => ({actions: bindActionCreators({...okrAction, resetUser, resetTeam, fetchAtList, clearAtList }, dispatch)}))
class ObjectiveDetail extends React.Component {

  state = {
    editItem: false,
    editObjective: false,
    editKeyResult: false,
    objective: null,
    keyResult: null,
    createItem: false,
    createObjective: false,
    createKeyResult: false,
    // 创建关键结果的目标Id
    objectiveId: null,
  };

  componentWillReceiveProps(props) {
    if (props.params.objectiveId != this.props.params.objectiveId) {
      this.props.actions.resetOkr();
      this.fetchContent(props);
    }
  }

  componentWillUnmount() {
    this.props.actions.resetUser();
    this.props.actions.resetTeam();
  }

  componentDidMount() {
    this.fetchContent();
  }

  fetchContent(props, excludeChildren, excludeAncester, refreshComments) {
    const { actions, params } = props || this.props;
    const { objectiveId } = params;
    // 更新目标
    actions.fetchObjectiveDetail(objectiveId);
    if (!excludeAncester) {
      // 更新上级目标
      actions.fetchObjectiveAncester(objectiveId);
    }
    if (!excludeChildren) {
      // 更新下级目标
      actions.fetchObjectiveChildren(objectiveId);
    }

    if (refreshComments) {
      this.refreshComments();
    }
  }

  // 刷新评论列表
  refreshComments(props) {
    const { actions, params } = props || this.props;
    const { objectiveId } = params;
    actions.reFetchOkrComments(objectiveId, { pageSize: commentsPageSize, pageNumber: 1 });
  }

  // 刷新目标:
  //  评论
  //  目标对象
  //  上级目标
  refreshObjective(excludeAncester) {
    this.fetchContent(null, true, excludeAncester);
    this.refreshComments();
  }

  // 刷新关键结果
  //  评论
  //  关键结果对象
  refreshKeyResult() {
    this.props.actions.fetchObjectiveDetail(this.props.params.objectiveId);
    this.refreshComments();
  }

  renderNav() {
    const { detail } = this.props.okr;
    if (util.isNull(detail)) return null;
    const { objectivePeriodName, objectivePeriodOwnerName } = detail;
    return (
      <div className={style.nav}>
        <Link to={`/okr?${util.body(this.props.location.query)}`} label={this.props.location.query.type == 1? '公司': objectivePeriodOwnerName}/>
        <Link
          className={style.period}
          label={objectivePeriodName}
          to={`/okr/${detail.objectivePeriodId}/objectives?${util.body(this.props.location.query)}`}
        />
      </div>
    );
  }

  render() {
    const {
      detail,
      comments,
    } = this.props.okr;
    const {
      editable,
      objectivePeriodId,
    } = detail || {};
    
    return (
      <div>
        <div className={style['nav-bar']}>
          { this.renderNav() }
        </div>
        <div className={style.content}>
          <ObjectiveItem 
            fetchContent={::this.fetchContent}
            objectiveCreatable={editable}
            objectiveEditable={editable}
            objectiveDeletable={editable}
            editObjective={() => requestEditObjective.call(this, detail)}
            editKeyResult={requestEditKeyResult.bind(this)}
            likeObjective={() => likeObjective.call(this, detail)}
            likeKeyResult={likeKeyResult.bind(this)}
            requestCreateKeyResult={requestCreateKeyResult.bind(this)}
            editObjectiveDetail
            refreshObjective={::this.refreshObjective}
            refreshKeyResult={::this.refreshKeyResult}
            obj={detail}
            {...detail}
            {...this.props}
          />
        </div>
        <div className={style['comment-relative']}>
          <div className={style.comments}>
            <h2>动态</h2>
            <ObjectiveNote
              className={style['comment-list']}
              active
              detail
              objectiveId={this.props.params.objectiveId}
              {...detail}
              {...this.props}
            />
          </div>
          <div className={style.relatives}>
            <ObjectiveRelative
              active
              detail
              editable={editable}
              editObjective={() => {
                if (util.isNull(detail)) return;
                requestEditObjective.call(this, detail)
              }}
              className={style['relative-list']}
              content={(detail || {}).content || ''}
              okr={this.props.okr}
              objectiveId={this.props.params.objectiveId}
              query={this.props.location.query}
            />
          </div>
        </div>
        <Modal
          active={this.state.editItem}
          title={this.state.editObjective? '编辑目标': '编辑关键结果'}
          onRequestClose={cancelRequestEditItem.bind(this)}
          actions={[
            'cancel',
            () => {
              if (this.state.editObjective) {
                updateObjective.call(this);
              } else {
                updateKeyResult.call(this);
              }
            }
          ]}
        >
          <ObjectiveCreate
            ref="objectiveEdit"
            submit={() => {
              if (this.state.editObjective) {
                updateObjective.call(this);
              } else {
                updateKeyResult.call(this);
              }
            }}
            editObjectiveDetail
            objectivePeriodId={objectivePeriodId}
            onRequestClose={cancelRequestEditItem.bind(this)}
            objective={this.state.objective}
            keyResult={this.state.keyResult}
            editObjective={this.state.editObjective}
            editKeyResult={this.state.editKeyResult}
            {...this.props}
          />
        </Modal>
        <Modal
          onRequestClose={cancelRequestCreateItem.bind(this)}
          active={this.state.createItem}
          title={this.state.createObjective? "创建目标": "添加关键结果"}
          className={style['objective-create-modal']}
          actions={[
            'cancel',
            () => {
              if (this.state.createObjective) this.createObjective();
              else createKeyResult.call(this);
            }
          ]}
        >
          <ObjectiveCreate
            ref="objectiveCreate"
            submit={() => {
              if (this.state.createObjective) this.createObjective();
              else createKeyResult.call(this);
            }}
            objectiveId={this.props.params.objectiveId}
            createObjective={this.state.createObjective}
            createKeyResult={this.state.createKeyResult}
            {...this.props}
          />
        </Modal>
      </div>
    );
  }
}
